<template>
  <div class="app-container">
    <!-- <mainTilte title="商品促销价格管理" /> -->
    <form-selections :is-active="true" :items="formItems" :query-param.sync="searchParams" display="block" @handleSearch="handleSearch" />
    <div class="select_flex">
      <div class="operation_button_box">
        <el-button v-action="'productSalesPrice@save'" size="small" type="success" icon="el-icon-circle-plus-outline" @click="add">
          新增促销价格</el-button>
        <el-button v-action="'productSalesPrice@batchExamine'" size="small" type="success" @click="submitReview">提交审核</el-button>
        <el-button v-action="'productSalesPrice@examine'" size="small" type="success" @click="examineClick">审核</el-button>
        <el-button v-action="'productSalesPrice@disable'" size="small" type="primary" @click="stopClick">禁用</el-button>
        <el-button v-action="'productSalesPrice@enable'" size="small" type="primary" @click="startClick">启用</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
      </div>
    </div>
    <div v-loading="loading" class="page-grid">
      <egrid
        :screen-heigh="screenHeigh"
        class="egrid"
        stripe
        fit
        border
        highlight-current-row
        element-loading-text="正在努力加载中..."
        :column-type="['selection']"
        :data="tableData"
        :columns="columns"
        :columns-schema="columnsSchema"
        :columns-handler="columnsHandler"
        @selection-change="checkIds"
      />
      <epagination v-if="tableData" :total="total" :current="searchParams.page" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
    </div>
    <!-- 新增 -->
    <el-dialog
      v-if="dialogAddVisible"
      v-loading.lock="loading"
      v-loading="loading"
      title=""
      :visible.sync="dialogAddVisible"
      :close-on-click-modal="false"
      width="90%"
      class="dialogText header-none"
      element-loading-text="正在加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      center
    >
      <el-form ref="formPrice" :model="form" :rules="roleCodeRule" label-width="120px">
        <el-row>
          <mainTilte title="模板基础信息" />
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model.trim="form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属店铺" prop="shop_id">
              <el-select v-model.trim="form.shop_id" filterable clearable placeholder="所属店铺" @change="changeShopHandler">
                <el-option v-for="(item, index) of shopList" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="时间" prop="start_time">
              <el-date-picker v-model="date" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :picker-options="datePickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="changeHandler" />
            </el-form-item>
            <!-- <el-form-item label="开始时间" prop="start_time">
              <el-date-picker v-model="form.start_time" class="filter-item" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="margin-right: 5px" placeholder="选择开始时间" />
            </el-form-item> -->
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="结束时间" prop="end_time">
              <el-date-picker v-model="form.end_time" class="filter-item" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="margin-right: 5px" placeholder="选择结束时间" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" autosize />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <mainTilte title="商品明细信息" class="mb0" />
        </el-row>
        <div class="operation_button_box">
          <el-button type="primary" @click="selectProduct">选择商品</el-button>
        </div>
        <el-table :data="form.product" stripe fit border>
          <el-table-column type="selection" width="55" />
          <el-table-column fixed="left" label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" style="color: #ff4444" @click="delClick(scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="原基准价" width="180" align="center" />
          <el-table-column label="促销基准价" prop="sales_price" min-width="180" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="'product.' + scope.$index + '.sales_price'" class="no-label" :rules="saleRules">
                <el-input-number v-model="scope.row.sales_price" :min="0" :precision="2" :max="9999999999" placeholder="请输入促销基准价" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="缩略图" width="150" align="center">
            <template slot-scope="scope">
              <thund :img="scope.row.image_url" />
            </template>
          </el-table-column>
          <el-table-column prop="product_code" label="系统sku" width="180" align="center" />
          <el-table-column prop="name_ch" label="中文名称" width="180" align="center" />
          <el-table-column prop="name_en" label="英文名称" width="180" align="center" />
          <el-table-column prop="type" label="商品类型" width="180" align="center" />
          <el-table-column prop="category_text" label="商品分类" width="180" align="center" />

        </el-table>
        <el-row style="text-align: center; margin-top: 20px">
          <span class="dialog-footer">
            <el-button type="primary" :loading="btnLoading" @click="saveProductData">保存</el-button>
            <el-button @click="cancelProductClick">取消</el-button>
          </span>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 审核 -->
    <el-dialog
      v-if="dialogExamineVisible"
      v-loading.lock="loading"
      v-loading="loading"
      title=""
      :visible.sync="dialogExamineVisible"
      :close-on-click-modal="false"
      width="90%"
      class="dialogText header-none"
      element-loading-text="正在加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      center
    >
      <priceDetails :form="detailsForm" />
      <el-form ref="examineForm" :model="examineForm" :rules="examineRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="">
              <el-radio-group v-model="examineForm.status">
                <el-radio :label="1">通过</el-radio>
                <el-radio :label="2">驳回</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="examineForm.status === 2" :span="16">
            <el-form-item label="驳回原因" prop="reason">
              <el-input v-model="examineForm.reason" type="textarea" autosize />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogExamineVisible = false">取消审核</el-button>
        <el-button type="primary" @click="saveExamineData()">确认审核</el-button>
      </span>
    </el-dialog>
    <!-- 添加商品 -->
    <el-dialog
      v-if="dialogAddProductVisible"
      v-loading.lock="loading"
      v-loading="loading"
      title=""
      :visible.sync="dialogAddProductVisible"
      :close-on-click-modal="false"
      width="90%"
      class="dialogText header-none"
      element-loading-text="正在加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      center
    >
      <addProduct :other-params="addProductParams" :issign-contract-codes="['shop-name']" @checkChildIds="checkChildIds" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddProductVisible = false">取消选择</el-button>
        <el-button type="primary" @click="saveData()">确认选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import list from '@/layout/mixin/list'
import operationBtnGroup from '@/components/base/operationBtnGroup'
import priceDetails from './components/details'
import dicValues from '@/components/dicTransform/index'
import dicTime from '@/components/dicTime/index'
import addProduct from '../portfolioManage/components/addPortProducts'
import codeItem from '@/components/base/code'
import {
  validPrice
} from '@/utils/validate'
import {
  action
} from '@/directive/permission/index.js' // 权限判断指令
import appText from '@/components/appText/index'
import {
  downloadxlsx
} from '@/utils/index'
import cacheList from '@/layout/mixin/cacheList'
export default {
  name: 'PromotionPriceManage',
  components: {
    priceDetails,
    addProduct
  },
  directives: {
    action
  },
  mixins: [list, cacheList],
  data() {
    const DICTIONARIES = {
      // 状态 2-禁用 1-启用
      isableList: [{
        code: 1,
        name: '启用'
      },
      {
        code: 2,
        name: '禁用'
      }
      ],
      statusList: [
        // 审核状态，0-待提交审核 1-审核通过 2-审核驳回 3-审核中
        {
          code: 0,
          name: '待提交'
        },
        {
          code: 1,
          name: '审核通过'
        },
        {
          code: 2,
          name: '审核驳回'
        },
        {
          code: 3,
          name: '待审核'
        }
      ]
    }
    return {
      otherHeight: 355,
      formItems: [{
        label: '模板名称',
        key: 'name',
        type: 'input',
        placeholder: '请输入模板名称'
      },
      {
        label: '所属店铺',
        key: 'shop_id',
        type: 'select',
        placeholder: '请选择店铺',
        filterable: true,
        options: []
      },
      {
        label: '审核状态',
        key: 'status',
        type: 'select',
        placeholder: '请选择审核状态',
        // 0-待提交审核 1-审核通过 2-审核驳回 3-审核中
        options: [
          {
            label: '待提交审核',
            value: '0'
          },
          {
            label: '审核通过',
            value: '1'
          },
          {
            label: '审核驳回',
            value: '2'
          },
          {
            label: '审核中',
            value: '3'
          }
        ]
      }
      ],
      componentName: 'PromotionPriceManage',
      cachePaths: [
        '/product/promotionPriceManage/promotionDetail'
      ],
      dialogAddProductVisible: false,
      checkChildList: [],
      shopList: [],
      rowData: {},
      /** *
         * 定义搜索框
         */
      searchParams: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        name: '',
        shop_id: '',
        status: ''
      },
      issignContract: [],
      loading: false,
      columns: [{
        label: '模板名称',
        prop: 'name',
        width: '200',
        align: 'center',
        tooltip: false,
        component: codeItem,
        propsHandler: function({
          row,
          col,
          column
        }) {
          return {
            code: row.name ? row.name : '',
            routePath: '/product/promotionPriceManage/promotionDetail',
            queryData: {
              id: row.id
            }
          }
        }
      },
      {
        label: '所属店铺',
        prop: 'shop_name',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '审核状态',
        prop: 'status',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '审核原因',
        prop: 'reason',
        width: '200',
        align: 'center',
        component: appText,
        propsHandler({
          row
        }) {
          return {
            text: row.reason
          }
        }
      },
      {
        label: '开始时间',
        prop: 'start_time',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '结束时间',
        prop: 'end_time',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '状态',
        prop: 'is_disable',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '备注',
        prop: 'remarks',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '创建人',
        prop: 'creator_name',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '创建时间',
        prop: 'created_at',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '修改人',
        prop: 'update_name',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '修改时间',
        prop: 'updated_at',
        width: '200',
        align: 'center',
        tooltip: false
      }
      ],
      columnsSchema: {
        状态: {
          propsHandler({
            col,
            row
          }) {
            return {
              dictionaries: DICTIONARIES['isableList'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        审核状态: {
          propsHandler({
            col,
            row
          }) {
            return {
              dictionaries: DICTIONARIES['statusList'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        开始时间: {
          propsHandler({
            col,
            row
          }) {
            return {
              code: row[col.prop]
            }
          },
          component: dicTime
        },
        结束时间: {
          propsHandler({
            col,
            row
          }) {
            return {
              code: row[col.prop]
            }
          },
          component: dicTime
        }
      },
      form: {
        name: '',
        shop_id: '',
        start_time: '',
        end_time: '',
        remarks: '',
        product: []
      },
      date: [],
      roleCodeRule: {
        name: [{
          required: true,
          message: '请输入模板名称',
          trigger: 'blur'
        },
        {
          max: 50,
          message: '模板名称必须在50个字符以内',
          trigger: 'blur'
        }
        ],
        shop_id: [{
          required: true,
          message: '请选择所属店铺',
          trigger: ['change', 'blur']
        }],
        start_time: [{
          required: true,
          message: '请选择开始时间',
          trigger: 'change'
        }],
        end_time: [{
          required: true,
          message: '请选择结束时间',
          trigger: 'change'
        }],
        remarks: [{
          max: 500,
          message: '备注必须在500个字符以内',
          trigger: 'blur'
        }]
      },
      btnLoading: false,
      saleRules: [{
        required: true,
        message: '请输入促销基准价',
        trigger: 'blur'
      },
      {
        validator(rule, value, callback) {
          if (!validPrice(value)) {
            callback(new Error('促销基准价必须是数字且保留两位小数'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
      ],
      products: [{
        picture: '',
        goods_code: '',
        number: ''
      }],
      dialogAddVisible: false,
      dialogExamineVisible: false, // 审核弹框
      examineForm: {
        value: '',
        status: 1,
        reason: ''
      },
      examineRules: {
        reason: [{
          required: true,
          message: '请输入驳回原因',
          trigger: 'blur'
        },
        {
          max: 500,
          message: '驳回原因必须是500个字符以内',
          trigger: 'blur'
        }
        ]
      },
      isEdit: false,
      detailsForm: {},
      datePickerOptions: {
        disabledDate(time) {
          const date = new Date()
          date.setDate(date.getDate() - 1)
          return time.getTime() < date.getTime()
        }
      },
      exportLoading: false
    }
  },
  computed: {
    addProductParams() {
      const vm = this
      return {
        shop_id: vm.form.shop_id,
        type: 0
      }
    }
  },
  created() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    this.query()
    this.queryShopAsync()
    this.getShop()
  },
  activated() {
    this.query()
    this.getShop()
  },
  methods: {
    // 获取店铺
    getShop() {
      const vm = this
      const params = { limit: 100000, page: 1 }
      vm.$http.get(`/shop`, { params: params }).then(res => {
        const data = res.data.map((arr) => {
          return {
            value: arr.id,
            label: arr.shop_name
          }
        })
        vm.formItems = vm.formItems.map(arr => {
          if (arr.key === 'shop_id') {
            arr.options = data
          }
          return arr
        })
      })
    },
    // 导出
    // handleExport() {
    //   const vm = this
    //   // vm.formVisibleDown = true
    //   vm.exportLoading = true
    //   const url = '/products/developmentProductExport'
    //   const {
    //     type,
    //     value,
    //     category_id,
    //   } = vm.searchParams
    //   const params = {
    //     category_id
    //   }
    //   if (type) {
    //     params[type] = value
    //   }
    //   vm.$http.post(url, params).then(res => {
    //     downloadxlsx(res.data)
    //     vm.exportLoading = false
    //   }).catch(() => {
    //     vm.exportLoading = false
    //   })
    // },

    // 修改店铺处理函数
    changeShopHandler(e) {
      this.form.product = []
    },
    // 修改日期处理函数
    changeHandler(e) {
      if (e && e.length === 2) {
        this.form.start_time = e[0]
        this.form.end_time = e[1]
      } else {
        this.form.start_time = ''
        this.form.end_time = ''
      }
    },
    handleSearch() {
      const vm = this
      vm.searchParams.page = 1
      vm.query()
    },
    handleRefresh() {
      const vm = this
      vm.searchParams.page = 1
      vm.searchParams.limit = 10
      vm.searchParams.name = ''
      vm.searchParams.status = ''
      vm.searchParams.shop_id = ''
      vm.query()
    },
    // 提交审核
    submitReview() {
      const dataLength = this.checkedList.length
      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }
      this.$confirm('确认要提交审核？', '', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          this.$http
            .post(`/productSalesPrice/batchExamine`, {
              ids: this.ids
            })
            .then(res => {
              if (res.code === 10000) {
                this.$message.success('提交审核成功')
                this.query()
              }
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(action => { })
    },
    // 禁用
    stopClick() {
      const vm = this
      const dataLength = vm.checkedList.length
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }

      vm.$confirm(`确定批量禁用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http
          .post(`/productSalesPrice/disable`, {
            ids: vm.ids
          })
          .then(res => {
            if (res.code === 10000) {
              vm.$message.success('禁用成功')
              vm.query()
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    startClick() {
      const vm = this
      const dataLength = vm.checkedList.length
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }
      vm.$confirm(`确定批量启用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http
          .post(`/productSalesPrice/enable`, {
            ids: vm.ids
          })
          .then(res => {
            if (res.code === 10000) {
              vm.$message.success('启用成功')
              vm.query()
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    editList() {
      this.$http
        .get(`/productSalesPrice/${this.rowData.id}`)
        .then(res => {
          if (res.code === 10000) {
            this.form = res.data
            this.form.product = res.data.list
            this.form.start_time = this.timestampToTime(this.form.start_time)
            this.form.end_time = this.timestampToTime(this.form.end_time)
            console.log(this.form.product, 'this.form.product')
            // console.log(typeof(this.form.start_time),'shijian')
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    // 时间戳转化成时间格式
    timestampToTime(timestamp) {
      // timestamp是整数，否则要parseInt转换,不会出现少个0的情况
      var time = new Date(timestamp * 1000)
      var year = time.getFullYear()
      var month = time.getMonth() + 1
      var date = time.getDate()
      var hours = time.getHours()
      var minutes = time.getMinutes()
      var seconds = time.getSeconds()
      return (
        year +
        '-' +
        this.add0(month) +
        '-' +
        this.add0(date) +
        ' ' +
        this.add0(hours) +
        ':' +
        this.add0(minutes) +
        ':' +
        this.add0(seconds)
      )
    },
    // 店铺查询
    queryShopAsync() {
      const params = {
        page: 1,
        limit: 100000000,
        status: 1
      }
      this.$http
        .get(`/shop`, {
          params
        })
        .then(res => {
          if (res.code === 10000 && res.data && res.data.length > 0) {
            this.shopList = res.data.map(item => {
              return {
                name: item.shop_name,
                id: item.id
              }
            })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 点击搜索
    query() {
      this.initTableData(
        `/productSalesPrice?page=${this.searchParams.page}&limit=${this.searchParams.limit}&name=${this.searchParams.name}&status=${this.searchParams.status}&shop_id=${this.searchParams.shop_id}`
      )
    },
    // 新增
    add() {
      this.form = {
        name: '',
        shop_id: '',
        start_time: '',
        end_time: '',
        remarks: '',
        product: []
      }
      this.date = []
      this.isEdit = false
      this.dialogAddVisible = true
    },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '200',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({
          row
        }) {
          return {
            row,
            edit: row.status !== 1,
            del: row.status !== 1,
            editAction: 'productSalesPrice@update',
            delAction: 'productSalesPrice@delete'
          }
        },
        component: operationBtnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          editTableClick(row) {
            that.$forceUpdate()
            that.rowData = row
            that.dialogAddVisible = true
            that.isEdit = true
            that.editList()
          },
          deleteTableClick(row) {
            that
              .$confirm('确认要删除？', '提示', {
                distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                that.$http
                  .delete(`/productSalesPrice/${row.id}`)
                  .then(res => {
                    if (res.code === 10000) {
                      that.$message.success('删除成功')
                      that.query()
                    }
                  })
                  .catch(err => {
                    console.log(err)
                  })
              })
          }
        }
      })
    },
    // 确认选择
    saveData() {
      const dataLength = this.checkChildList.length

      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }

      const firstShopId = this.checkChildList[0].shop_id
      const isSameShopId = this.checkChildList.every(
        e => e.shop_id === firstShopId
      )
      if (!isSameShopId) {
        this.$message.error('所选择的数据必须所属同一个店铺')
        return
      }
      console.log(this.checkChildList)
      this.form.shop_id = this.checkChildList[0].shop_id
      this.checkChildList.forEach(ele => {
        const index = this.form.product.findIndex(
          e => e.product_id === ele.product_id
        )
        if (index > -1) {
          this.form.product.splice(index, 1)
        }
        const productObj = {
          image_url: ele.image_url,
          product_code: ele.product_code,
          name_ch: ele.name_ch,
          name_en: ele.name_en,
          type: ele.type === 0 ? '内部员工' : '客户商品', // 商品所属客户类型 0-内部员工 1-客户商品
          category_name: ele.category_name, // 商品分类
          category_text: ele.category_text, // 商品分类
          price: this.getPrice(ele), // 基准价
          number: 0,
          product_id: ele.product_id
        }
        this.form.product.push(productObj)
      })
      this.dialogAddProductVisible = false
    },
    // 获取基准价
    getPrice(item) {
      //  type 0 内部商品 1 客户商品
      if (!item.type) {
        return item.benchmark_price
      } else {
        item.purchase_price_usd = +item.purchase_price_usd
        item.purchase_price_rmb = +item.purchase_price_rmb
        return item.purchase_price_usd || item.purchase_price_rmb
      }
    },
    checkChildIds(data) {
      this.checkChildList = data
    },
    createStateFilter(queryString) {
      return state => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        )
      }
    },
    handleSelect() { },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000
    },
    saveProductData() {
      this.$refs['formPrice'].validate(valid => {
        if (valid) {
          if (this.form.product.length <= 0) {
            return this.$message.error('请至少选择添加一个商品')
          }
          this.btnLoading = true
          const data = JSON.parse(JSON.stringify(this.form))
          let param = {
            start_time: this.getTimestamp(data.start_time),
            end_time: this.getTimestamp(data.end_time)
          }
          const newObj = Object.assign(data, param)
          param = JSON.parse(JSON.stringify(newObj))
          if (this.isEdit) {
            delete param.created_at
            delete param.updated_at
            // 编辑
            this.$http
              .put(`/productSalesPrice/${this.form.id}`, param)
              .then(res => {
                if (res.code === 10000) {
                  this.$message.success('修改促销成功')
                  this.query()
                  this.dialogAddVisible = false
                }
                this.btnLoading = false
              })
              .catch(err => {
                this.btnLoading = false
                console.log(err)
              })
          } else {
            this.$http
              .post(`/productSalesPrice`, param)
              .then(res => {
                if (res.code === 10000) {
                  this.$message.success('新增促销成功')
                  this.query()
                  this.dialogAddVisible = false
                  this.isEdit = false
                }
                this.btnLoading = false
              })
              .catch(err => {
                this.btnLoading = false
                console.log(err)
              })
          }
        }
      })

      // this.form.start_time = this.getTimestamp(this.form.start_time)
      // this.form.end_time = this.getTimestamp(this.form.end_time)
    },
    cancelProductClick() {
      this.dialogAddVisible = false
      this.isEdit = false
    },
    // 点击审核按钮
    examineClick() {
      const dataLength = this.checkedList.length
      if (dataLength === 0 || dataLength > 1) {
        this.$message.error('请至多选择一条数据')
        return false
      }
      // 不是待审核的数据不能
      if (this.checkedList[0].status !== 3) {
        return this.$message.error('所选数据必须是待审核数据')
      }
      this.$http
        .get(`/productSalesPrice/${this.checkedList[0].id}`)
        .then(res => {
          if (res.code === 10000) {
            this.detailsForm = res.data
            this.detailsForm.list = res.data.list.map(e => {
              const {
                parent_name,
                category_name
              } = e
              e['category_text'] = `${parent_name}-${category_name}`
              return e
            })
          }
        })
      this.dialogExamineVisible = true
      this.examineForm.status = 1
      this.examineForm.reason = ''
    },
    // 确认审核
    saveExamineData() {
      const vm = this
      vm.$refs.examineForm.validate(valid => {
        if (valid) {
          const param = {
            status: vm.examineForm.status,
            reason: vm.examineForm.reason
          }
          vm.$http
            .put(`/productSalesPrice/examine/${vm.checkedList[0].id}`, param)
            .then(res => {
              if (res.code === 10000) {
                vm.$message.success('确认审核成功')
                vm.query()
              }
            })
            .catch(err => {
              console.log(err)
            })
          vm.dialogExamineVisible = false
        }
      })
    },
    // 选择商品
    selectProduct() {
      if (!this.form.shop_id) {
        return this.$message.error('请选择所属店铺')
      }
      this.dialogAddProductVisible = true
    },
    delClick(row) {
      this.form.product = this.form.product.filter(item => {
        return item !== row
      })
      this.$forceUpdate()
    },
    handleSizeChange(val) {
      this.searchParams.limit = val
      this.query()
    },
    handleCurrentChange(val) {
      this.searchParams.page = val
      this.query()
    }
  }
}

</script>

<style scoped>
.addExpense {
  padding: 15px;
  background: #fff;
}

.app-container /deep/.el-select,
.el-autocomplete,
.el-date-editor {
  width: 100%;
}

.sizeStyle {
  display: flex;
}

.sizeStyle /deep/ .el-input__inner {
  border-right: 0;
}

.sizeStyle /deep/ .el-input-group__append {
  padding-left: 4px;
  padding-right: 4px;
  font-size: 14px;
  color: #333333;
  background: #fff;
}
</style>
